package com.ysucode.controller.user.advice;

import com.ysucode.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义校验验证码的过滤器————在Security原有过滤器基础上的增强
 * 这里没用到，因为登录时不需要验证码，后续考虑再添加
 */
@Component
public class CheckCodeFilter extends GenericFilterBean {
    @Autowired
    private UserService userService;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String defaultFilterProcessUrl = "/loginServlet"; //设置默认的拦截路径
//        if ("POST".equalsIgnoreCase(request.getMethod()) && defaultFilterProcessUrl.equals(request.getServletPath())) {
//            String code = request.getParameter("checkcodelog");
//            User user = userService.getByUsername(request.getParameter("username"));
//            String checkcodegenlog = (String) request.getSession().getAttribute("checkcodegenlog");
//            if (checkcodegenlog == null) return;
//            if (!code.equalsIgnoreCase(checkcodegenlog)) { //验证码错误
//                req.setAttribute("error", new Result(Constant.LOGIN, Constant.USER_CODE_ERR));
//                req.getRequestDispatcher("/login").forward(req, res);
//                return;
//                //throw new AuthenticationServiceException("验证码错误!");
//            } else if (user == null) {
//                req.setAttribute("error", new Result(Constant.LOGIN, Constant.USER_ERR));
//                req.getRequestDispatcher("/login").forward(req, res);
//                return;
//            }
//        }
        //放行
        chain.doFilter(request, response);
    }
}
